package com.pickerview.dialog;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.pickerview.PickViewConst;
import com.pickerview.R;
import com.pickerview.lib.MapKeyComparator;
import com.pickerview.lib.ScreenInfo;
import com.pickerview.lib.WeekCheckView;
import com.pickerview.lib.WeekCheckView.OnWeekCheckListener;
import com.pickerview.lib.WheelDate;
import com.pickerview.lib.WheelHourMin;
import com.pickerview.lib.WheelOptions;
import com.pickerview.lib.listener.OnConfirmListener;
import com.pickerview.lib.listener.OnOptionsSelectListener;
import com.pickerview.lib.listener.OnTimeComfirmListener;

/**
 * com.pickerview.dialog.CommonPickDialog
 * @author jiyuren <br/>
 * create at 2015年5月26日 下午5:17:44
 */
public class CommonPickDialog extends Dialog implements android.view.View.OnClickListener {
  private static final String TAG = "CommonPickDialog";
  
  public enum Type {
    TIME_TIME, OPTIONS, CUSTOM,CUSTOM_OPTIONS,YM_YM
  }// 开始时间-开始时间,其它选项，自定义,年月-年月

  WheelOptions wheelOptions;
  private OnOptionsSelectListener optionsSelectListener;

  private View rootView; // 总的布局
  WheelHourMin wheelHourMin;
  WheelDate wheelDate;
  private Button btnSubmit, btnCancel;
  private static final String TAG_SUBMIT = "submit";
  private static final String TAG_CANCEL = "cancel";
  private StringBuilder weekBuilder = new StringBuilder();
  private StringBuilder weekIndexBuilder = new StringBuilder();
  private String weekIndex = "";
  private String weekIndexCopy = "";
  private String week = "";
  private String weekCopy = "";
  private Context context;
  private Type type;
  WeekCheckView weekCheckView;
  private LinearLayout llTop;
  
  LinearLayout llCon;
  
  public CommonPickDialog(Context context) {
    super(context, R.style.dialog);
    init(context);
  }
  public CommonPickDialog(Context context, int theme) {
    super(context, theme);
    init(context);
  }
  public CommonPickDialog(Context context,Type type) {
    super(context, R.style.dialog);
    this.type = type;
    init(context);
  }
  public CommonPickDialog(Context context,int theme,Type type) {
    super(context, theme);
    this.type = type;
    init(context);
    
  }
  /**
   * 添加自定义view 到dialog
   * @param view
   */
  public void addView(View view){
    if(null!=llCon){
      llCon.addView(view);
    }
  }
  /**
   * 添加标题栏
   * @param view
   */
  public void addTitleView(View view){
    if(null!=llTop){
      llTop.addView(view);
    }
  }
  
  /**
   * @param context2
   */
  private void init(Context context) {
    this.context = context;
    
    LayoutInflater mLayoutInflater = LayoutInflater.from(context);

    // ----时间转轮
    ScreenInfo screenInfo = new ScreenInfo((Activity) context);

    switch (type) { 
      case YM_YM://年月 
        rootView = mLayoutInflater.inflate(R.layout.dialog_date_date, null);
        View dateView = rootView.findViewById(R.id.include_date_);
        wheelDate = new WheelDate(dateView);
        wheelDate.screenheight = screenInfo.getHeight();
        break;
      case TIME_TIME:
        rootView = mLayoutInflater.inflate(R.layout.dialog_time_time, null);
        weekCheckView = (WeekCheckView) rootView.findViewById(R.id.week_view);
        weekCheckView.setOnWeekCheckListener(myWeekCheckLisnter);
        View timeView = rootView.findViewById(R.id.include_time);
        wheelHourMin = new WheelHourMin(timeView);
        wheelHourMin.screenheight = screenInfo.getHeight();
        for (int i = 0; i < WeekCheckView.WEEKS.length; i++) {
          weekBuilder.append(WeekCheckView.WEEKS[i]).append("、");
          if (i == 0) {
            weekIndexBuilder.append(WeekCheckView.WEEKS.length + "").append("|");
            continue;
          }
          weekIndexBuilder.append(i + 1).append("|");
        }
        week = "周" + weekBuilder.toString().substring(0, weekBuilder.toString().lastIndexOf("、"));
        weekCopy = week;
        weekIndex = weekIndexBuilder.toString().substring(0, weekIndexBuilder.toString().lastIndexOf("|"));
        weekIndexCopy = weekIndex;
        break;

      case OPTIONS:
        rootView = mLayoutInflater.inflate(R.layout.dialog_options_options, null);
        // ----转轮
        final View optionspicker = rootView.findViewById(R.id.include_options);
        wheelOptions = new WheelOptions(optionspicker);
        wheelOptions.screenheight = screenInfo.getHeight();
        llTop = (LinearLayout) rootView.findViewById(R.id.ll_top);
        break;
      case CUSTOM:
        rootView = mLayoutInflater.inflate(R.layout.pw_custom_view,null);
        llCon = (LinearLayout) rootView.findViewById(R.id.ll_con);
        break;
      case CUSTOM_OPTIONS:
        rootView = mLayoutInflater.inflate(R.layout.dialog_options_options, null);
        // ----转轮
        final View viewPicker = rootView.findViewById(R.id.include_options);
        wheelOptions = new WheelOptions(viewPicker);
        wheelOptions.screenheight = screenInfo.getHeight();
        llTop = (LinearLayout) rootView.findViewById(R.id.ll_top);
        
        break;
    }
  }
  /**
   *
   */
  @SuppressLint({ "NewApi", "ResourceAsColor" })
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // -----确定和取消按钮
    
    btnSubmit = (Button) rootView.findViewById(R.id.bt_sure);
    btnSubmit.setBackgroundResource(PickViewConst.BT_CONFIRM_BG);
    btnSubmit.setTextColor(context.getResources().getColorStateList(PickViewConst.BT_CONFIRM_TEXT));
    btnSubmit.setTag(TAG_SUBMIT);
    
    btnCancel = (Button) rootView.findViewById(R.id.bt_cancle);
    btnCancel.setBackgroundResource(PickViewConst.BT_CANCLE_BG);
    btnCancel.setTextColor(context.getResources().getColorStateList(PickViewConst.BT_CANCLE_TEXT));
    
    btnCancel.setTag(TAG_CANCEL);
    
    btnSubmit.setOnClickListener(this);
    btnCancel.setOnClickListener(this);
    
    
    setContentView(rootView);
  }
  
  /**
   * 设置week 选中
   * @param index
   */
  public void setWeekCheck(int...index){
    if(null!=weekCheckView){
      weekCheckView.setWeekChecked(index);
    }
  }
  
  @Override
  public void onClick(View v) {

    String tag = (String) v.getTag();
    if (tag.equals(TAG_CANCEL)) {
      dismiss();
      return;
    } else {
      switch (type) {
        case YM_YM:
          initTime(type);
          break;
        case TIME_TIME:
          initTime(type);
          break;
        case OPTIONS:
          initOptions();
          break;
        case CUSTOM:
          if(null!=confirmListener){
            confirmListener.onConfirm();
            dismiss();
          }
          break;
        case CUSTOM_OPTIONS:
          initOptions();
          break;
      }
      return;
    }
  }
  /**
   * 独立双集合
   * @param options1Items
   * @param options2Items
   */
  public void setPicker(List<String> options1Items,List<String> options2Items) {
    wheelOptions.setPicker(options1Items, options2Items,null);
  }
  /**
   * 独立三集合
   * @param options1Items
   * @param options2Items
   * @param options3Items
   */
  public void setPicker(List<String> options1Items,List<String> options2Items,List<String> options3Items) {
    wheelOptions.setPicker(options1Items, options2Items,options3Items);
  }
  public void setPicker(List<String> optionsItems) {
    wheelOptions.setPicker(optionsItems, null, null, false);
  }

  public void setPicker(List<String> options1Items, List<List<String>> options2Items, boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, null, linkage);
  }

  public void setPicker(List<String> options1Items, List<List<String>> options2Items,
      List<List<List<String>>> options3Items, boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, options3Items, linkage);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   */
  public void setSelectOptions(int option1) {
    wheelOptions.setCurrentItems(option1, 0, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   */
  public void setSelectOptions(int option1, int option2) {
    wheelOptions.setCurrentItems(option1, option2, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   * @param option3
   */
  public void setSelectOptions(int option1, int option2, int option3) {
    wheelOptions.setCurrentItems(option1, option2, option3);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1) {
    wheelOptions.setLabels(label1, null, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1, String label2) {
    wheelOptions.setLabels(label1, label2, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   * @param label3
   */
  public void setLabels(String label1, String label2, String label3) {
    wheelOptions.setLabels(label1, label2, label3);
  }

  /**
   * 设置时间范围
   * @param startHourLs
   * @param startMinLs
   * @param endHourLs
   * @param endMinLs
   */
  public void setRangeTime(List<String> startHourLs, List<String> startMinLs, List<String> endHourLs,
      List<String> endMinLs) {
    wheelHourMin.setTime2TimePicker(startHourLs, startMinLs, endHourLs, endMinLs);
  }
  /**
   * 设置时间范围
   * @param startHourLs
   * @param startMinLs
   * @param endHourLs
   * @param endMinLs
   */
  public void setRangeDate(List<String> startYearLs, List<String> startMonLs, List<String> endYearLs,
      List<String> endMonLs) {
    wheelDate.setTime2TimePicker(startYearLs, startMonLs, endYearLs, endMonLs);
  }

  private OnWeekCheckListener myWeekCheckLisnter = new OnWeekCheckListener() {
    @Override
    public void onWeekCheckListener(Map<Integer, String> map) {
      StringBuilder sbWeek = new StringBuilder();
      StringBuilder sbWeekIndex = new StringBuilder();
      if (!map.isEmpty()) {
        Map<Integer, String> resultMap = MapKeyComparator.sortMapByKey(map);
        for (Map.Entry<Integer, String> entry : resultMap.entrySet()) {
          sbWeek.append(entry.getValue()).append("、");
          if (entry.getKey() == 0) {
            sbWeekIndex.append(WeekCheckView.WEEKS.length + "" ).append("|");
            continue;
          }
          sbWeekIndex.append(entry.getKey() + "").append("|");
        }
        week = "周" + sbWeek.toString().substring(0, sbWeek.toString().lastIndexOf("、"));
        weekIndex = sbWeekIndex.toString().substring(0, sbWeekIndex.toString().lastIndexOf("|"));
      } else {
        week = weekCopy;
        weekIndex = weekIndexCopy;
      }
    }
  };

  /**
   * 设置是否循环滚动
   * 
   * @param cyclic
   */
  public void setCyclic(boolean cyclic) {
    switch (type) {
      case YM_YM:
        wheelDate.setCyclic(cyclic);
        break;
      case TIME_TIME:
        wheelHourMin.setCyclic(cyclic);
        break;
      case OPTIONS:
        wheelOptions.setCyclic(cyclic);
        break;
      case CUSTOM:
        break;
      case CUSTOM_OPTIONS:
        wheelOptions.setCyclic(cyclic);
        break;
        
    }
  }

  public void setVisibleItems(int count) {
    switch (type) {
      case YM_YM:
        wheelDate.setVisibleItems(count);
        break;
      case TIME_TIME:
        wheelHourMin.setVisibleItems(count);
        break;
      case OPTIONS:
        wheelOptions.setVisibleItems(count);
        break;
      case CUSTOM:
        break;
      case CUSTOM_OPTIONS:
        wheelOptions.setVisibleItems(count);
        break;
    }
  }
  /**
   * 
   */
  private void initOptions() {
    if (optionsSelectListener != null) {
      int[] optionsCurrentItems = wheelOptions.getCurrentItems();
      optionsSelectListener.onOptionsSelect(optionsCurrentItems[0], optionsCurrentItems[1], optionsCurrentItems[2]);
    }
    dismiss();
  }

  /**
   * 
   */
  private void initTime(Type type) {
    if (null != onComfirmListener) {
      
      switch (type) {
        case YM_YM:
          int startYear = Integer.valueOf(wheelDate.getTimeRange()[0]);
          int startMonth = Integer.valueOf(wheelDate.getTimeRange()[1]);
          int endYear = Integer.valueOf(wheelDate.getTimeRange()[2]);
          int endMonTh = Integer.valueOf(wheelDate.getTimeRange()[3]);

          if (startYear > endYear && endYear!=0) {
            Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
            return;
          }
          if (startYear == endYear) {
            if (startMonth > endMonTh) {
              Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
              return;
            }
            if (startMonth == endMonTh && endMonTh!=0) {
              Toast.makeText(context, "开始时间和结束时间不能相同", 0).show();
              return;
            }
          }
          Calendar calendar = Calendar.getInstance();
          int year = calendar.get(Calendar.YEAR);
          int month = calendar.get(Calendar.MONTH)+1;
          if((startYear==year && startMonth>month)
              || (endYear==year && endMonTh>month)){
            Toast.makeText(context, "开始时间或者结束时间不能大于当前时间", 0).show();
            return;
          }
          
          String times[] = new String[]{ wheelDate.getTimeRange()[0], wheelDate.getTimeRange()[1],
              wheelDate.getTimeRange()[2], wheelDate.getTimeRange()[3]};
          
          onComfirmListener.onTimeConfirm(times);
          break;
        case TIME_TIME:
          int startHour = Integer.valueOf(wheelHourMin.getTimeRange()[0]);
          int startMin = Integer.valueOf(wheelHourMin.getTimeRange()[1]);
          int endHour = Integer.valueOf(wheelHourMin.getTimeRange()[2]);
          int endMin = Integer.valueOf(wheelHourMin.getTimeRange()[3]);

          String time = wheelHourMin.getTimeRange()[0] + ":" + wheelHourMin.getTimeRange()[1] + "-" + wheelHourMin.getTimeRange()[2]
              + ":" + wheelHourMin.getTimeRange()[3];
          if (startHour > endHour) {
            Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
            return;
          }
          if (startHour == endHour) {
            if (startMin > endMin) {
              Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
              return;
            }
            if (startMin == endMin) {
              Toast.makeText(context, "开始时间和结束时间不能相同", 0).show();
              return;
            }
          }
          onComfirmListener.onTimeConfirm(week, weekIndex.toString(), time);
          break;
      }
      dismiss();
    }
  }

  private OnTimeComfirmListener onComfirmListener;
  private OnConfirmListener confirmListener;
  /**
   * 时间选择
   * @param onComfirmListener
   */
  public void setOnTimeComfirmListener(OnTimeComfirmListener onComfirmListener) {
    this.onComfirmListener = onComfirmListener;
  }
  /**
   * 其他选项时选择
   * @param optionsSelectListener
   */
  public void setOnoptionsSelectListener(OnOptionsSelectListener optionsSelectListener) {
    this.optionsSelectListener = optionsSelectListener;
  }
  
  /**
   * 自定义dialog view 时 设置监听
   * @param confirmListener
   */
  public void setOnConfirmListener(OnConfirmListener confirmListener){
    this.confirmListener = confirmListener;
  }
  
 
}
